package org.example.mrrope.service;

import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.utils.DingUtil;
import org.example.mrrope.utils.FormUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * CYQ
 * 缝纫 车间下发派工单
 */
@Service
@Slf4j
public class FengRenWorkOrder {

    @Autowired
    private DingUtil dingUtil;

    public Integer getFengRen(JSONObject upJsonA, String id, String userId) throws Exception {
        String s = null;
        //获取半成品子表里的数据,一个半成品生成一条配件信息
        //判断半成品子表里是否有数据
        if (upJsonA.has("tableField_lwed3a1x")) {
            // 查询半成品BOM
            JSONArray jsonArrTow = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lwed3a1x");
            List<String> list2 = new ArrayList<>();
            JSONObject upJsonE = new JSONObject();
            //-------------------------------BOM里面的数据赋值------------------------------------------
            upJsonE.put("dateField_m3hhuwkv", upJsonA.has("dateField_m2wwkxe0") ? upJsonA.get("dateField_m2wwkxe0") : "");//完成时间
//            upJsonE.put("numberField_lugarhfl", upJsonA.has("numberField_lx41w1sv") ? upJsonA.get("numberField_lx41w1sv") : "");//订单总数
            //循环半成品BOM
            for (int i = 0; i < jsonArrTow.length(); i++) {
                //半成品b号
                String numberB = "";
                JSONObject jsInBOM = jsonArrTow.getJSONObject(i);
                JSONObject upJsonB = new JSONObject(upJsonE.toString());
                if (jsInBOM.has("textField_lujgt592")) {
                    numberB = (String) jsInBOM.get("textField_lujgt592");
                    upJsonB.put("textField_lugarhfd", numberB);//半成品B号
                }
                //--------------------------------------------------------------------------------------------------
                //查询当前半成BOM里面的是否需要缝纫
                JSONObject searchFieldJson = new JSONObject();
                //查询半成BOM
                searchFieldJson.put("textField_lujgt576", numberB);
                String yiDaSearchReturnData_XSDD = dingUtil.yiDaSearchReturnData("FORM-916B5F5CEECE4FB5ADD382411F8DCFF9FSLS", searchFieldJson);//获取半成品
                JSONArray yiDaSearchReturnData_XSDDJsonArray = new JSONArray(yiDaSearchReturnData_XSDD);
                JSONObject xsddJSONObject = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getJSONObject("formData");
                String SOID = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getString("formInstanceId");
                //判断是否有缝纫
//                String isFengRen = "否";
                if (xsddJSONObject.has("radioField_m61ug5ca")){
                    if (xsddJSONObject.get("radioField_m61ug5ca").equals("否")){
                        continue;
                    }
                }else{
                    continue;
                }
                //--------------------------------------------------------------------------------------------------
                //判断半成品是不是仅采购,仅采购结束循环
                if (jsInBOM.has("radioField_m4qllfwm")) {
                    if (jsInBOM.getString("radioField_m4qllfwm").equals("是")) {
                        continue;
                    }
                }

                String typePeiJian = null;
                //--------------------关联半成品BOM----------------------
                String title = numberB;
                String fromUuid = "FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K";
                // 通过调用FormUtils的getAssociationFormField方法，根据fromUuid、title和id获取关联表单字段的JSON数组
                JSONArray jsonArrayOne = FormUtils.getAssociationFormField(fromUuid, title, id);
                upJsonB.put("associationFormField_lwt4miug", jsonArrayOne);


                //---------------------------------配件赋值----------------------------------------------------------
                if (upJsonA.has("tableField_lvxe56yi")) {
                    JSONArray peiJianArray = dingUtil.getInnerTables(id, "FORM-916B5F5CEECE4FB5ADD382411F8DCFF9FSLS", "tableField_lvxe56yi");
                    ArrayList<JSONObject> listOneFenRen = new ArrayList<>();
                    //-------配件子表----------
                    for (int j = 0; j < peiJianArray.length(); j++) {
                        JSONObject peiJianObject = peiJianArray.getJSONObject(j);
                        JSONObject fenRen = new JSONObject();
                        String numberD = (String) peiJianObject.get("textField_lx07bljk");
                        //判断是否是当前半成品对应的配件信息
                        if (!numberB.equals(numberD)) {
                            continue;
                        }
                        if (peiJianObject.has("radioField_lxsgdwtr")) {
                            typePeiJian = (String) peiJianObject.get("radioField_lxsgdwtr");
                            if (typePeiJian.equals("缝纫")) {
                                fenRen.put("textField_lx07bljk", peiJianObject.get("textField_lx07bljk"));//半成品B号
                                fenRen.put("textField_lujgt59d", peiJianObject.get("textField_lujgt59d"));//配件名称
                                fenRen.put("textField_lujgt59f", peiJianObject.get("textField_lujgt59f"));//配件编号
                                fenRen.put("textField_lx3ck53r", peiJianObject.get("textField_lx3ck53r"));//规格描述
                                fenRen.put("textField_lx2luc3t", peiJianObject.get("textField_lx2luc3t"));//是否打孔
                                fenRen.put("textField_lx2luc3s", peiJianObject.has("textField_lx2luc3s") ? peiJianObject.get("textField_lx2luc3s") : "");//打孔规格
                                fenRen.put("textField_lwg902pd", peiJianObject.has("textField_lwg902pd") ? peiJianObject.get("textField_lwg902pd") : "");//供应商
                                fenRen.put("imageField_lwg902pf", peiJianObject.has("imageField_lwg902pf") ? peiJianObject.get("imageField_lwg902pf") : "");//例图
                                fenRen.put("textField_lwee5prf", peiJianObject.get("textField_lwee5prf"));//备注
                                fenRen.put("numberField_lxwv7czp", peiJianObject.has("numberField_lxwv7czp") ? peiJianObject.get("numberField_lxwv7czp") : 0);//配件总领量数
                                fenRen.put("numberField_m607z7r2", peiJianObject.has("numberField_m4hx46fs") ? peiJianObject.get("numberField_m4hx46fs") : 0);//实际配件总领量数
                                fenRen.put("numberField_lxvgkgg8", peiJianObject.get("numberField_lz6dt0zj"));//标准用量
//                                fenRen.put("numberField_lxvgkgg8", peiJianObject.get("numberField_lz6dt0zj"));//标准用量
                                fenRen.put("radioField_lxsgdwtr", peiJianObject.get("radioField_lxsgdwtr"));//类型
                                listOneFenRen.add(fenRen);
                            }
                        }
                    }
                    upJsonB.put("tableField_lvxe56yi", listOneFenRen);//配件
                    log.info("缝纫-配件----------------" + listOneFenRen);
//                    if (listOneFenRen.size() <= 0) {
//                        continue;
//                    } else {
//
//                    }
                }
//                else {
//                    continue;
//                }
                //--------------------------------半成品BOM里面的数据赋值----------------------------------------------
                upJsonB.put("numberField_lugarhfl", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : "");//生产总量
                upJsonB.put("numberField_m607z7r1", jsInBOM.has("numberField_m5z1tmyo") ? jsInBOM.get("numberField_m5z1tmyo") : "");//实际生产总量
                upJsonB.put("numberField_m3ho60sa", jsInBOM.has("numberField_lxvgkgg7") ? jsInBOM.get("numberField_lxvgkgg7") : 0);//标准用量
                upJsonB.put("numberField_lzc3l82w", jsInBOM.has("numberField_m4w3ia5e") ? jsInBOM.get("numberField_m4w3ia5e") : "");//工价
                //----------------------------------------绳子赋值----------------------------------------------------
                ArrayList<JSONObject> listTowFengRen = new ArrayList<>();
                JSONObject shengZiObject = null;
                if (upJsonA.has("tableField_lujgt57k")) {
                    JSONArray yanSeArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lujgt57k");
                    for (int k = 0; k < yanSeArray.length(); k++) {
                        shengZiObject = yanSeArray.getJSONObject(k);
                        //判断是否是当前半成品对应的绳子信息
                        if (shengZiObject.has("textField_lx07bljm")) {
                            String numberC = (String) shengZiObject.get("textField_lx07bljm");
                            if (!numberB.equals(numberC)) {
                                continue;
                            }
                        }
                        JSONObject shengZiFengRen = new JSONObject();
                        shengZiFengRen.put("textField_lxxbi9ma", shengZiObject.get("textField_lujgt57l"));//半成品绳子C号
                        shengZiFengRen.put("textField_lxxbi9mb", shengZiObject.get("textField_lxd6qtml"));//绳子名称
                        shengZiFengRen.put("numberField_lxxbi9me", shengZiObject.has("numberField_lujhx4e2") ? shengZiObject.get("numberField_lujhx4e2") : "");//辅机重量
                        shengZiFengRen.put("textareaField_lxxbi9mf", shengZiObject.has("textareaField_lvxhxh0a") ? shengZiObject.get("textareaField_lvxhxh0a") : "");//花色挂法
                        shengZiFengRen.put("textField_lxxbi9md", shengZiObject.has("textField_lxipl733") ? shengZiObject.get("textField_lxipl733") : "");//规格
                        shengZiFengRen.put("numberField_lxxbi9mc", shengZiObject.has("numberField_lujhx4e0") ? shengZiObject.get("numberField_lujhx4e0") : "");//绳子口径
                        shengZiFengRen.put("numberField_lxxbi9mg", shengZiObject.has("numberField_lz6dt0zh") ? shengZiObject.get("numberField_lz6dt0zh") : "");//标准用量
                        shengZiFengRen.put("numberField_lxxbi9mh", shengZiObject.has("numberField_lxwv7czn") ? shengZiObject.get("numberField_lxwv7czn") : "");//绳子总领量数
                        shengZiFengRen.put("numberField_m607z7r2", shengZiObject.has("numberField_m5z1tmyq") ? shengZiObject.get("numberField_m5z1tmyq") : "");//实际绳子总领量数
                        shengZiFengRen.put("selectField_lxxbi9mi", shengZiObject.has("selectField_lxtpnbg4") ? shengZiObject.get("selectField_lxtpnbg4") : "");//绳子口径
                        listTowFengRen.add(shengZiFengRen);
                    }
                }
                upJsonB.put("tableField_lxwy3kxi", listTowFengRen);//绳子
                upJsonB.put("radioField_m42cd3fr", "正常");//派工单状态
                JSONObject searchScheduleJson = new JSONObject();
                searchScheduleJson.put("textField_lyz6ump9", upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//so号
                searchScheduleJson.put("textField_lugarhfd", numberB);//半成品号
                String yiDaSearchReturnData_Schedule = dingUtil.yiDaSearchReturnData("FORM-92DE151B85C34929A6DA955418128ABBHU7O", searchScheduleJson);//获取缝纫派工单数据
                JSONArray yiDaSearchReturnData_ScheduleJsonArray = new JSONArray(yiDaSearchReturnData_Schedule);
                if (!yiDaSearchReturnData_ScheduleJsonArray.isEmpty()) {
                    String oid = yiDaSearchReturnData_ScheduleJsonArray.getJSONObject(0).getString("formInstanceId");
                    JSONObject zsObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                    Double todoAmount = jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.getDouble("numberField_lxwv7czo") : 0.0;//应有的待完成量
                    Double finishedAmount = zsObject.has("numberField_m2ucw3c9") ? zsObject.getDouble("numberField_m2ucw3c9") : 0.0;//已上缴
                    Double dispatchedAmount = zsObject.has("numberField_m5f2f440") ? zsObject.getDouble("numberField_m5f2f440") : 0.0;//已下发作业
                    Double receivedAmount = zsObject.has("numberField_m3y7tjon") ? zsObject.getDouble("numberField_m3y7tjon") : 0.0;//已入库量
                    upJsonB.put("numberField_m2ucw3c8", todoAmount - finishedAmount);//上缴
                    upJsonB.put("numberField_m5f2f43z", todoAmount - dispatchedAmount);//已下发作业
                    upJsonB.put("numberField_m3hhuwkw", todoAmount - receivedAmount);//已入库·
                    log.info("更新 缝纫车间派工单开始");
                    log.info("更新oid:{}", oid);
                    log.info("更新数据:{}", upJsonB);
                    dingUtil.UpdateYiDa(oid, upJsonB);//更新生产计划
                    log.info("更新 缝纫车间派工单完成");
                } else {
                    upJsonB.put("textField_lugarhgb", upJsonA.has("textField_lxk8d6fp") ? upJsonA.get("textField_lxk8d6fp") : "");//注意点
                    upJsonB.put("radioField_mann5ewv", upJsonA.has("radioField_makqj7pi") ? upJsonA.get("radioField_makqj7pi") : "苍南");//工厂
                    upJsonB.put("textField_lx1mddjk", upJsonA.has("textField_lujgt578") ? upJsonA.get("textField_lujgt578") : "");//客户名称
                    upJsonB.put("textField_lugarhfc", upJsonA.has("radioField_m3iilehf") ? upJsonA.get("radioField_m3iilehf") : "");//
                    upJsonB.put("radioField_m3iilehf", upJsonA.has("textField_m2e5ira7") ? upJsonA.get("textField_m2e5ira7") : "");//PO
                    upJsonB.put("textField_lyz6ump9", upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//SO号
                    upJsonB.put("textField_lugarhfe", upJsonA.has("textField_lujgt577") ? upJsonA.get("textField_lujgt577") : "");//客人货号
                    upJsonB.put("textField_lugarhfx", jsInBOM.has("textareaField_m2ohpz46") ? jsInBOM.get("textareaField_m2ohpz46") : "");//规格/重量
                    upJsonB.put("imageField_lugarhfm", jsInBOM.has("imageField_lwt5fomx") ? jsInBOM.get("imageField_lwt5fomx") : "");//图片
                    upJsonB.put("textField_lxifktd1", jsInBOM.has("textField_lwbmqipz") ? jsInBOM.get("textField_lwbmqipz") : "");//名称
                    upJsonB.put("numberField_m2ucw3c9", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : "");//未上缴
                    upJsonB.put("numberField_m5f2f440", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : "");//未下发作业
                    upJsonB.put("numberField_m3y7tjon", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : "");//未入库
                    s = dingUtil.startInstance(upJsonB, userId, "FORM-92DE151B85C34929A6DA955418128ABBHU7O");
                    log.info("YIDA-startInstance 缝纫车间派工单生成流程完成" + s);
                }
                list2.add(numberB);
            }
            //查找现有的派工单，进行循环，多余的派工单删除
            //根据SO号搜索
            JSONObject paiGonJson = new JSONObject();
            paiGonJson.put("textField_lyz6ump9", upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//so号
            String yiDaPaiGonString = dingUtil.yiDaSearchReturnData("FORM-92DE151B85C34929A6DA955418128ABBHU7O", paiGonJson);//获取派工单数据
            JSONArray yiDaPaiGonJsonArray = new JSONArray(yiDaPaiGonString);
            HashMap<String, String> newMap = new HashMap<>();
            List<String> list1 = new ArrayList<>();
            //把C号存在容器里面
            for (int i = 0; i < yiDaPaiGonJsonArray.length(); i++){
                String oid = yiDaPaiGonJsonArray.getJSONObject(i).getString("formInstanceId");
                JSONObject pgdObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                if (pgdObject.has("textField_lugarhfd")){
                    list1.add(pgdObject.getString("textField_lugarhfd"));
                    newMap.put(pgdObject.getString("textField_lugarhfd"),oid);
                }
            }
            // 找出派工单中有但生产计划中没有的元素
            // 派工单 减 生产计划 多出来的就是没用的派工单
            list1.removeAll(list2);
            if (list1.size() > 0){
                for (String numberB : list1) {
                    //删除多余的派工单
                    if (newMap.containsKey(numberB)){
                        JSONObject object = new JSONObject();
                        object.put("radioField_m42cd3fr", "暂停");
                        dingUtil.UpdateYiDa(newMap.get(numberB), object);
//                        dingUtil.(newMap.get(numberB));
                    }
                }
            }
        }
        return s == null ? 1 : 0;
    }
}
